package com.childenglish.validation;

import com.childenglish.utils.DataEncryptionUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 加密模式匹配验证器
 */
public class EncryptedPatternValidator implements ConstraintValidator<EncryptedPattern, String> {
    
    private Pattern pattern;
    
    @Override
    public void initialize(EncryptedPattern constraintAnnotation) {
        int flags = 0;
        for (javax.validation.constraints.Pattern.Flag flag : constraintAnnotation.flags()) {
            flags |= flag.getValue();
        }
        this.pattern = Pattern.compile(constraintAnnotation.regexp(), flags);
    }
    
    @Override
    public boolean isValid(String encryptedValue, ConstraintValidatorContext context) {
        // 如果值为空或null，则跳过验证
        if (encryptedValue == null || encryptedValue.trim().isEmpty()) {
            return true;
        }
        
        try {
            // 尝试解密
            String value = DataEncryptionUtils.decrypt(encryptedValue);
            // 验证格式
            return pattern.matcher(value).matches();
        } catch (Exception e) {
            // 如果解密失败，可能是明文，直接验证
            return pattern.matcher(encryptedValue).matches();
        }
    }
}

